import { ref, watch } from 'vue'

// 倒计时
export const useCountDown = (num = 60) => {
  // 倒计时数
  const count = ref(num)
  // 是否倒计时中
  const isDown = ref(false)
  // 定时器
  let timer = null
  // 开始倒计时
  const start = () => {
    isDown.value = true
    timer = setInterval(() => {
      count.value--
    }, 1000)
  }

  // 监听倒计时数
  watch(count, (newCount) => {
    if (newCount < 1) {
      clearInterval(timer)
      isDown.value = false
      count.value = num
    }
  })
  return {
    count,
    isDown,
    start,
  }
}
